using System;
using System.Collections.Generic;
using System.Text;
using Barrage.Global;
using NLog;

namespace Barrage.Audios
{
    /// <summary>
    /// AudioFileManager holds a list of already loaded AudioFiles to avoid loading them from disk twice.
    /// </summary>
    public class AudioFileManager
    {
        private static Logger logger = NLog.LogManager.GetLogger("Barrage::AudioFileManager");
        private static AudioFileManager instance=null;

        /// <summary>
        /// Class instance
        /// </summary>
        public static AudioFileManager Audios { get { if (instance == null) instance = new AudioFileManager(); return instance; } }

        private AudioFileManager() { createDefaultAudioFile(); }
        private Dictionary<string, AudioFile> AudioFiles=new Dictionary<string,AudioFile>();

        private AudioFile defaultAudioFile;
        /// <summary>
        /// Gets the default audio file that will be heard when no sound is found
        /// </summary>
        public static AudioFile DefaultAudioFile{get{return instance.defaultAudioFile;}}

        private void createDefaultAudioFile(){
            defaultAudioFile = new SimpleAudioFile(Store.PathConfig[Store.AUDIO_PATH]+"default.wav");
        }

        /// <summary>
        /// Tries to load the specified file (or returns it if already loaded).
        /// If the load throws an error, the default sound is returned
        /// </summary>
        /// <param name="name">Sound file name</param>
        /// <returns>An AudioFile instance, loaded from the specified file, or DefaultAudio if it couldn't be loaded</returns>
        public AudioFile this[string name]
        {
            get
            {
                AudioFile t=null;
                if (AudioFiles.TryGetValue(name,out t))
                    return t;
                logger.Debug("AudioFile " + name + " not found. Trying to load");
                try
                {
                    t = new SimpleAudioFile(Store.PathConfig[Store.AUDIO_PATH]+name);
                    logger.Debug("AudioFile " + name + " finished loading.");
                }
                catch{
                    logger.Debug("Error loading AudioFile " + name);
                    t = DefaultAudioFile;
                }
                AudioFiles.Add(name, t);
                return t;
            }
        }
    }

}
